package com.lmh.framework.jwt;

import com.github.pagehelper.util.StringUtil;
import com.lmh.entity.User;
import com.lmh.framework.exception.MyException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JWTUtil {

    // 请求头名称
    public static String token = "token";

    // 签名密钥
    public static String SECRET = "19301035@bjtu.edu.cn";

    // 过期时长
    public static long EXPR = 3600 * 24 * 1000;

    // 1.生成Token
    public static String sign(User user) {
        // 1.指定签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        // 2.生成发行时间
        long nowMillis = System.currentTimeMillis();
        Date date = new Date(nowMillis);
        // 3.创建payload的私有声明
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("userName", user.getUserName());
        // 4.生成签发人
        String subject = user.getUserName();

        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(date)
                .setSubject(subject)
                .signWith(signatureAlgorithm, SECRET);

        // 5.生成过期时间
        Date exprDate = new Date(nowMillis + EXPR);
        builder.setExpiration(exprDate);

        return builder.compact();
    }

    // 2.验证Token
    public static boolean verify(String token) {
        try {
            if (StringUtil.isEmpty(token)) {
                return false;
            }
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 3.获取用户信息
    public static User getUser(String token) {
        try {
            if (StringUtil.isEmpty(token)) {
                throw new MyException("token不能为空");
            }
            if (verify(token)) {
                Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
                User user = new User();
                user.setId(Integer.parseInt(claims.get("id") + ""));
                user.setUserName((String) claims.get("userName"));
                return user;
            } else {
                throw new MyException("超时或token不合法");
            }
        } catch (Exception e) {
            throw new MyException("超时或token不合法");
        }
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setUserName("admin");
        String token = sign(user);
        System.out.println(getUser(token));
    }
}
